package cn.oms.oms.service.impl;

import cn.oms.oms.entity.*;
import cn.oms.oms.exception.ServiceException;
import cn.oms.oms.mapper.*;
import cn.oms.oms.service.IAccountService;
import cn.oms.oms.vo.AccountVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AllenChen曾晨
 * @since 2022-04-29
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements IAccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private PatientMapper patientMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private PickingMapper pickingMapper;


    /**
     * 查询缴费单列表
     * @param accountVo
     * @return
     */
    @Override
    public PageInfo<Account> selectAccountList(AccountVo accountVo) {

        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();

        List<Integer> patientIdList = new ArrayList<>();

        List<Integer> billAccountIdList = new ArrayList<>();

        // 根据患者名称模糊查询
        if (StringUtil.isNotEmpty(accountVo.getPatientName())){
            QueryWrapper<Patient> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.like("patientName",accountVo.getPatientName());
            queryWrapper1.eq("deleteFlag",0);
            List<Patient> patientList = patientMapper.selectList(queryWrapper1);
            if (patientList.size()>0&&patientList!=null){
                for (Patient patient:patientList){
                    patientIdList.add(patient.getPatientId());
                }
            }
            //患者ID列表去重
            patientIdList = patientIdList.stream().distinct().collect(Collectors.toList());

            // 根据患者ID查询账单
            if (patientIdList.size()>0&&patientIdList!=null){
                QueryWrapper<Bill> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.in("patientId",patientList);
                queryWrapper2.eq("billingFlag",1);
                queryWrapper2.eq("deleteFlag",0);
                List<Bill> billList = billMapper.selectList(queryWrapper2);
                if(billList.size()>0&&billList!=null){
                    for (Bill bill:billList){
                        billAccountIdList.add(bill.getAccountId());
                    }
                }
            }
            // 账单ID列表去重
            billAccountIdList = billAccountIdList.stream().distinct().collect(Collectors.toList());

            if (billAccountIdList!=null&&billAccountIdList.size()>0){
                //根据账单ID查询所有账单
                queryWrapper.in("accountId",billAccountIdList);
            }
        }

        if (accountVo.getPayFlag()!=null&&!"".equals(accountVo.getPayFlag())){
            queryWrapper.eq("payFlag",accountVo.getPayFlag());
        }


        queryWrapper.eq("deleteFlag",0);
        PageHelper.startPage(accountVo.getPageNum(),accountVo.getPageSize());
        List<Account> accounts = accountMapper.selectList(queryWrapper);
        if (accounts.size()==0||accounts==null){
            throw new ServiceException("参数异常，缴费单列表为空");
        }

        // 时间初始化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(Account account:accounts){
            if (account.getCreateTime()!=null){
                account.setReturnCreateTime(format.format(account.getCreateTime()));
            }
            if (account.getPayTime()!=null){
                account.setReturnPayTime(format.format(account.getPayTime()));
            }
        }

        return new PageInfo<>(accounts);
    }

    /**
     * 查询缴费单详情
     * @param accountVo
     * @return
     */
    @Override
    public Account selectAccountDetail(AccountVo accountVo) {

        if (accountVo.getAccountId()==null||"".equals(accountVo.getAccountId())){
            throw new ServiceException("参数异常，缴费单ID不能为空");
        }
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accountId",accountVo.getAccountId());
        queryWrapper.eq("deleteFlag",0);

        Account account = accountMapper.selectOne(queryWrapper);
        if (account==null){
            throw new ServiceException("参数异常，缴费单信息不存在");
        }

        // 数据格式化
        // 时间初始化
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (account.getCreateTime()!=null){
            account.setReturnCreateTime(format.format(account.getCreateTime()));
        }
        if (account.getPayTime()!=null){
            account.setReturnPayTime(format.format(account.getPayTime()));
        }

        return account;
    }

    /**
     * 新增缴费单
     * @param accountVo
     * @return
     */
    @Override
    public String addAccount(AccountVo accountVo) {
        return null;
    }

    /**
     * 修改缴费单
     * @param accountVo
     */
    @Override
    public String updateAccount(AccountVo accountVo) {
        return null;
    }

    /**
     * 缴费单缴费
     * @param accountVo
     */
    @Override
    public String accountPay(AccountVo accountVo) {

        if (accountVo.getAccountId()==null||"".equals(accountVo.getAccountId())){
            throw new ServiceException("参数异常，缴费单ID不能为空");
        }
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accountId",accountVo.getAccountId());
        queryWrapper.eq("deleteFlag",0);

        Account account = accountMapper.selectOne(queryWrapper);
        if (account==null){
            throw new ServiceException("参数异常，缴费单信息不存在");
        }

        //判断是否已经缴费过了
        if (account.getPayFlag()==1){
            throw new ServiceException("参数异常，缴费单已缴费，不可重复缴费！！！");
        }

        if(account.getItemTotalPrice()==null||"".equals(account.getItemTotalPrice())){
            throw new ServiceException("参数异常，后端查询缴费总价为空");
        }
        if(accountVo.getPayPrice()==null||"".equals(accountVo.getPayPrice())){
            throw new ServiceException("参数异常，前端传入缴费价格为空");
        }

        // 比较是否相等
        int num = account.getItemTotalPrice().compareTo(accountVo.getPayPrice());
        if (num!=0){
            throw new ServiceException("参数异常，缴费价格与缴费总价不匹配，缴费失败");
        }

        account.setPayFlag(1);
        account.setPayTime(new Date());
        num = accountMapper.updateById(account);
        if (num!=1){
            throw new ServiceException("数据库修改异常，缴费单信息修改失败");
        }

        //获取所有账单对应的医嘱ID
        List<Integer> orderIdList = new ArrayList<>();

        //将缴费单对应的账单和捡药发药数据更新
        //更新账单信息
        QueryWrapper<Bill> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("billingFlag",1);
        queryWrapper1.eq("accountId",account.getAccountId());
        queryWrapper1.eq("deleteFlag",0);
        List<Bill> billList = billMapper.selectList(queryWrapper1);
        if (billList.size()>0&&billList!=null){
            for (Bill bill:billList){
                bill.setBillPayFlag(1);
                int i = billMapper.updateById(bill);
                if (i!=1){
                    throw new ServiceException("数据库修改异常，账单信息修改失败");
                }
                orderIdList.add(bill.getOrderId());
            }
        }

        if (orderIdList.size()>0&&orderIdList!=null){
            //更新捡药发药信息
            QueryWrapper<Picking> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("orderId",orderIdList);
            queryWrapper.eq("deleteFlag",0);
            List<Picking> pickingList = pickingMapper.selectList(queryWrapper2);
            if(pickingList.size()>0&&pickingList!=null){
                //遍历捡药发药
                for (Picking picking:pickingList){
                    picking.setPayFlag(1);
                    int i = pickingMapper.updateById(picking);
                    if (i!=1){
                        throw new ServiceException("数据库修改异常，捡药发药信息修改失败");
                    }
                }
            }
        }


        return "ok";
    }
}
